<?php
namespace App\Services;

use GTClient;
use GTNotification;
use GTPushMessage;
use GTPushRequest;
use Illuminate\Support\Facades\Log;

class GeTuiService
{
    static public function push($title, $content, $deviceId)
    {
        $api = new GTClient(
            "https://restapi.getui.com",
            config('app.getui_appkey'),
            config('app.getui_appid'),
            config('app.getui_mastersecret'),
        );

        SELF::pushIOS($api, $title, $content, $deviceId);
        SELF::pushAndroid($api, $title, $content, $deviceId);

        return true;
    }
    static private function pushIOS($api, $title, $content, $deviceId)
    {
        $push = new GTPushRequest();
        $push->setRequestId(md5(time() . mt_rand(1, 9999999)));
        $message = new GTPushMessage();
        $message->setTransmission(
            json_encode([
                'type' => 'receive',
                'msg'=> $title.':'.$content
            ])
        );
        $push->setPushMessage($message);
        $push->setCid($deviceId);
        $result = $api->pushApi()->pushToSingleByCid($push);
        return $result;
    }

    static private function pushAndroid($api, $title, $content, $deviceId)
    {
        $push = new GTPushRequest();
        $push->setRequestId(md5(time() . mt_rand(1, 9999999)));
        $message = new GTPushMessage();
        $notify = new GTNotification();
        $notify->setTitle($title);
        $notify->setBody($content);
        $notify->setClickType("none");
        $message->setNotification($notify);
        $push->setPushMessage($message);
        $push->setCid($deviceId);
        $result = $api->pushApi()->pushToSingleByCid($push);
        return $result;
    }
}
